#include<iostream>
#include<pthread.h>
#include<vector>
#include<unistd.h>
#include<string>

#define NUM 10
//__thread int g_val = 0;//线程的局部存储
int g_val = 0;
struct threadData
{
    std::string _tid;
    std::string _threadname;
};
//转换为16进制
std::string toHex(pthread_t tid)
{
    char buf[128];
    snprintf(buf, sizeof(buf), "0x%x", tid);
    return buf;
}
void* threadRoutine(void* args)
{
    //pthread_detach(pthread_self());
    threadData* td = static_cast<threadData*>(args);
    int i = 0;
    while(i < 10)
    {
        std::cout << "pid: " << getpid() << ", tid: " << toHex(pthread_self()) <<", threadname: " << td->_threadname 
                << ", g_val: " << g_val << ", &g_val: " << &g_val << std::endl;
        sleep(1);
        i++;
        g_val++;
    }
    delete td;
    return nullptr;
}
void InitThreadData(threadData* td, int num)
{
    td->_threadname = "thread-" + std::to_string(num);
}    
int main()
{
    std::vector<pthread_t> tids;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData;
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
        sleep(1);
    }
    // for(auto i : tids)
    // {
    //     pthread_detach(i);
    // }
    for(int i = 0; i < tids.size(); i++)
    {
        int n = pthread_join(tids[i], nullptr);
        std::cout << "n = " << n << " who = " << tids[i];
    }
    return 0;
}